package ink.ykb.demo.permission.config;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

import ink.ykb.demo.config.CodeConstant;
import ink.ykb.demo.config.MessageUtil;
import ink.ykb.demo.config.ServiceException;
import ink.ykb.demo.permission.annotation.Function;
import ink.ykb.demo.permission.service.UserPermissionService;


/**
 * 权限拦截
 * @author mading
 *
 */
@Configuration
@Aspect
@Order(100)
public class FunctionAccessCheckAop {

  @Autowired
  private UserPermissionService userPermissionService;
  @Autowired
  private MessageUtil messageUtil;
  
  @Around("execution(* ink.ykb.demo..*.*(..)) && @annotation(function)")
  public Object functionAccessCheck(final ProceedingJoinPoint pjp, Function function) throws Throwable {
      String funCode = null;
      try {
          
          if (function != null) {
              funCode = function.value();
              boolean access = userPermissionService.canAcessFunction(funCode);
              if (!access) {
                throw new ServiceException(CodeConstant.ACCESS_DENIED,messageUtil.getMsg(CodeConstant.ACCESS_DENIED));
              }
          }
          
          return pjp.proceed();

      } catch (Throwable e) {
          throw e;
      }

  }
  
  

}
